package com.cangxuan.backend.wrapper;

import com.alibaba.fastjson.JSONObject;
import com.cangxuan.backend.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.util.*;

@Slf4j
public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {
    private String getRequestBody(InputStream stream) {
        String line = "";
        StringBuilder body = new StringBuilder();
        int counter = 0;

        // 读取POST提交的数据内容
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        try {
            while ((line = reader.readLine()) != null) {
                if (counter > 0) {
                    body.append("rn");
                }
                body.append(line);
                counter++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return body.toString();
    }

    private HashMap<String, String[]> getParamMapFromPost(HttpServletRequest request) {

        String body = "";
        try {
            body = getRequestBody(request.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        HashMap<String, String[]> result = new HashMap<String, String[]>();

        if (null == body || 0 == body.length()) {
            return result;
        }

        return parseQueryString(body);
    }


    public HashMap<String, String[]> parseQueryString(String s) {
        String valArray[] = null;
        if (s == null) {
            throw new IllegalArgumentException();
        }
        HashMap<String, String[]> ht = new HashMap<String, String[]>();
        StringTokenizer st = new StringTokenizer(s, "&");
        while (st.hasMoreTokens()) {
            String pair = (String) st.nextToken();
            int pos = pair.indexOf('=');
            if (pos == -1) {
                continue;
            }
            String key = pair.substring(0, pos);
            String val = pair.substring(pos + 1, pair.length());
            if (ht.containsKey(key)) {
                String oldVals[] = (String[]) ht.get(key);
                valArray = new String[oldVals.length + 1];
                for (int i = 0; i < oldVals.length; i++) {
                    valArray[i] = oldVals[i];
                }
            } else {
                valArray = new String[1];
            }
            ht.put(key, valArray);
        }
        return ht;
    }

    private Map<String, String[]> getParamMapFromGet(HttpServletRequest request) {
        return parseQueryString(request.getQueryString());
    }

    // 报文
    private byte[] body;

    public String getBody() {
        return new String(body);
    }

    public void setBody(String bodypa) {
        body = bodypa.getBytes();
    }


    private String rsaPrivateKey = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCEhRzjKKmy29vRGGhuWmR7XTtWBlmhvnejm7ZE+RLqR2vAeDcT/sOTh2WDtsaFuLJlWOxgE+fkva4ZsJGwibhonrOUnNYA8Q/thn1D6CePFDeJfCmrIGR8ed8IW8Olnzrumy2xAYy/WLd4UCFihfnmJHo0bUpgMasftJHsKmFBVIubJxspDBVKpwBtA4Lkv31VJMYfq7ftwST9HeihsoW2yfppDwfBkefuMpw8gGeiR5bsH/AlaUg2gHyMsPYUWkaKBXvw7X7ce+WCjS4L9T8X2abujcRPa133Kz9nS0McGIJ5He4Mj/wGha0m09HpT2DcNlXBXYXrEAAsK59lkjIrAgMBAAECggEAQPsk1x6xV8sHVtipHLOmYfetiNlESlOjRs6r6dZYuBiddZt9JojeThEubg/J+PhAQgIApnwcUcXRATfbuL1Pd72aQV1Gct/B967i7dGA1GANe5UuuYMAwyjffLHClgwmUao2FX21Dn7qOEzSkgUwLPHmGp8cwV6ZkspwY2XEmsuoer00PjqeA/GPWYwM0pShR5pbpBEk/3WL17W7XAy2S6KGcdfKViUere4h2xVCrpFhL5CepKkC01EUm46YdhssuKekL4K6Nmo5wAWsnaEXCV5xVq6vaA85+XMXaWscG+E0jHIPVdpEIRiB9fsQTE55fXECMsmWhqZmy0NARkwbwQKBgQDp2WN0XdVB5ncrlzZL+NJ1oprZkFaaM6MKLnWYhYgesGR9smK1fWQigllfXpzTgfDvN2tJUM3BFWqprtNeXe9z0C6ItY7oeVx/3eYuFjE65D0xa/OgeVpiK/NohxTUQdNFk3j3eEZyugJejqUpJf832aMuIkZ+RO61S1mHqxd/pQKBgQCREpdeLc/u3r3LL/OHW9Kdjf40NDm0QB6m5+G1XIgQy/NEmNyoknFJIAlKjxAkoi+nonb55CkCurSCh+7lGyTjxlwKsOUKz66ICfx8x3PveFTOTspFTdMFyz3Sso/9/xBGifMAVJvsHbLjagCYxZ39tO7M10TXNoBE8CnBfZVBjwKBgGPd5s9HU0+1cKc5CIMhXB/ItYC8V3+7FaG/fZEJVbxlcEUN7YG8bwsdx7Um3qqlD5PZgwPocjZHQyn782CVlTFMctMHVmSJj6s7xJVh/Nw9pLR6eazKpoLOakD1jzumcOeBt2NYBh3wuhpPqNEN3RSo6TtGf/xky9y4tR9vPbXRAoGAVQvlGR0aTRrfgQJ3bd7ytdLMN6Z2PalpTseZlkzMp6wozQogMeLH7uqNB9yexhsefNPNk+mh8SurLuqprj4ffjiHNO1HGPNviejwz+XNnZGZhejCw6ZAE6F2eNKdf3XMAM5WWtc/IUi32oIGH4maeWVcqVF51gDpaYCxufD5UxkCgYBbwcP20+OnbpIWJm5SGT+0MLx9j23jmw2Ls8pbQ8MMOOy3s//aAVwGCx2/KJv2ITb+V4IkMoE6mreB1XBn/cyEjXmgi3jZU0D0WOK1143U2o8Xmbs2p3G7Ga+oRUHK1Oe00iSUJb6WkbaJTAXktnjEIkMX8e52n+t87H47D2CWWQ==";

    public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        if (request.getMethod().toUpperCase().equals("POST")) {
            body = readBytes(request.getInputStream());
            JSONObject jsonBody = JSONObject.parseObject(getBody());
            if (jsonBody != null) {
                String aesKeyEncrypt = jsonBody.getString("key");
                String aesKeyDecrypt = SecurityUtils.decryptRSA(rsaPrivateKey, aesKeyEncrypt);
                String data = jsonBody.getString("data");
                log.info("解密之前的body:" + data);
                String jsonValueString = SecurityUtils.decryptAES(aesKeyDecrypt, data);
                log.info("解密之后的body:" + jsonValueString);
                JSONObject jsonValue = JSONObject.parseObject(jsonValueString);
                if (jsonBody.containsKey("other")) {
                    jsonValue.put("other", jsonBody.getString("other"));
                }
                setBody(jsonValue.toJSONString());
            }
        }
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body);
        return new ServletInputStream() {

            @Override
            public int read() throws IOException {
                return bais.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener arg0) {

            }
        };
    }

    private static byte[] readBytes(InputStream in) throws IOException {
        BufferedInputStream bufin = new BufferedInputStream(in);
        int buffSize = 1024;
        ByteArrayOutputStream out = new ByteArrayOutputStream(buffSize);

        byte[] temp = new byte[buffSize];
        int size = 0;
        while ((size = bufin.read(temp)) != -1) {
            out.write(temp, 0, size);
        }
        bufin.close();

        byte[] content = out.toByteArray();
        return content;
    }

}
